//
// Created by guanyicheng on 2022/9/2.
//
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */

#include "../../common.h"

class Solution {

    int getDepth(TreeNode *root) {
        int left = 0, right = 0;
        if (root->left != nullptr) {
            left = getDepth(root->left);
        }
        if (root->right != nullptr) {
            right = getDepth(root->right);
        }
        if (left == -1 || right == -1) {
            return -1;
        }
        int d = left - right;
        d = d > 0 ? d : -d;
        if (d > 1) {
            return -1;
        }
        return (left > right ? left : right) + 1;
    }

public:
    bool isBalanced(TreeNode *root) {
        if (root == nullptr) {
            return true;
        }
        return getDepth(root) != -1;
    }
};